package com.example.mypra1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.spark.submitbutton.SubmitButton;
import com.example.mypra1.adapter.MyListAdapter;
import com.example.mypra1.adapter.entity.Project;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 登录
 */
public class LoginActivity extends AppCompatActivity {
    private TextView go_reg;
    private SubmitButton submit_btn;
    private EditText username_edt,password_edt;
    private Handler handler=new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            String token = (String) msg.obj;
            SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
            editor.putString("token",token);//存储token
            editor.commit();
            Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_LONG).show();
            Intent intent = new Intent(LoginActivity.this,HomeActivity.class);//跳转至首页
            startActivity(intent);
            finish();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        submit_btn = findViewById(R.id.submit);
        username_edt = findViewById(R.id.username);
        password_edt = findViewById(R.id.password);
        go_reg = findViewById(R.id.go_reg);
        go_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//跳转注册界面
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
        submit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = username_edt.getText().toString();
                String password = password_edt.getText().toString();
                SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                editor.putString("phone",phone);
                editor.putString("password",password);
                editor.commit();
                getData(phone,password);
            }
        });
    }
    //发送post请求，验证用户信息并获取token
    private void getData(String phone,String password){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    FormBody formBody = new FormBody.Builder()
                            .add("phone",phone).add("password",password).build();
                    Request request = new Request.Builder()
                            .url("http://8.142.19.67:3000/login")
                            .post(formBody)
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                try {
                                    JSONObject jsonObject = new JSONObject(res);
                                    if (jsonObject.getString("token").equals("null")) {
                                        return;
                                    } else {
                                        String token = jsonObject.getString("token");
                                        JSONObject user = jsonObject.getJSONObject("data");
                                        SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                                        editor.putInt("id", user.getInt("id"));
                                        editor.putString("username",user.getString("username"));
                                        editor.putString("phone",user.getString("phone"));
                                        editor.putString("password",user.getString("password"));
                                        editor.putInt("sex",user.getInt("sex"));
                                        editor.putString("profile",user.getString("profile"));
                                        editor.putString("zodiac",user.getString("zodiac"));
                                        editor.putString("constellation",user.getString("constellation"));
                                        editor.commit();//将用户信息和token存储到SharedPreference中
                                        Message message = new Message();
                                        message.obj = token;
                                        handler.sendMessage(message);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}